package com.nwpu.hass.utils.qrcodeutils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;

import com.google.zxing.BarcodeFormat;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;

/**
 * ZXing二维码生成/解码
 * @author phil
 * @date 2017年8月30日
 *
 */
public class QRCodeUtil {

    /**
     * 生成二维码图片
     */
    public static File toQRCode(String content, String savePath, String remark) {
        int width = 400, height = 400;
        try {
            BufferedImage bim = toBufferedImage(content, BarcodeFormat.QR_CODE, width, height, toDecodeHintType());
            return encode(bim,  savePath,  remark);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 是否需要给二维码图片添加Logo
     */
    private static File encode(BufferedImage bim, String savePath,  String remark) {
        ByteArrayOutputStream baos = null;
        try {
            BufferedImage image = bim;
            if ( StringUtils.isNotBlank(remark)){
                // 新的图片，把带logo的二维码下面加上文字
                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // 画二维码到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 画文字到新的面板
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("微软雅黑", Font.BOLD, 20)); // 字体、字型、字号
                int strWidth = outg.getFontMetrics().stringWidth(remark);
                if (strWidth > 399) {
                    String productName1 = remark.substring(0, remark.length() / 2);
                    String productName2 = remark.substring(remark.length() / 2);
                    int strWidth1 = outg.getFontMetrics().stringWidth(productName1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(productName2);
                    outg.drawString(productName1, 200 - strWidth1 / 2, image.getHeight() + (outImage.getHeight() - image.getHeight()) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    outg2.setFont(new Font("微软雅黑", Font.BOLD, 30)); // 字体、字型、字号
                    outg2.drawString(productName2, 200 - strWidth2 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } else {
                    outg.drawString(remark, 200 - strWidth / 2, image.getHeight() + (outImage.getHeight() - image.getHeight()) / 2 + 12); // 画文字
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }
            image.flush();
            File file = new File(savePath);
            ImageIO.write(image, "png", file);//直接写入某路径
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(baos);
        }
        return null;
    }

    /**
     * 生成二维码bufferedImage图片
     * @param content 编码内容
     * @param barcodeFormat 编码类型
     * @param width 图片宽度
     * @param height 图片高度
     * @param hints 设置参数
     */
    private static BufferedImage toBufferedImage(String content, BarcodeFormat barcodeFormat, int width, int height,
                                                 Map<EncodeHintType, ?> hints) {
        MultiFormatWriter multiFormatWriter;
        BitMatrix bitMatrix ;
        BufferedImage image = null;
        try {
            multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            bitMatrix = multiFormatWriter.encode(content, barcodeFormat, width, height, hints);
            int w = bitMatrix.getWidth();
            int h = bitMatrix.getHeight();
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? MatrixToImageConfig.BLACK : MatrixToImageConfig.WHITE);
                }
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 设置二维码的格式参数
     */
    private static Map<EncodeHintType, Object> toDecodeHintType() {
        // 用于设置QR二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 设置QR二维码的纠错级别（H为最高级别）具体级别信息
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置编码方式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 0);
        return hints;
    }
}
